package com.luoqiwen.android.sinaurldecoder

import android.os.Bundle
import android.text.method.ScrollingMovementMethod
import android.util.Log
import android.view.View.INVISIBLE
import android.view.View.VISIBLE
import android.widget.*
import androidx.appcompat.app.AppCompatActivity
import com.google.android.material.button.MaterialButton
import kotlinx.coroutines.*

class MainActivity : AppCompatActivity() {
    companion object {
        lateinit var INSTANCE: MainActivity
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        INSTANCE = this
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        MainScope().launch(Dispatchers.Main) {
            debug("正在启动 SinaURLDecoder by luoqiwen")
            debug("Copyright © 2022 luoqiwen(starforeal). All Rights Reserved")
            debug("开源地址: https://gitee.com/shinyforeal/SinaURLDecoder")
            debug("正在启动...")

            debug("注册Listener...")
            findViewById<MaterialButton>(R.id.execute).setOnClickListener(ExecuteBtnListener(this@MainActivity))
            findViewById<ImageButton>(R.id.clickClip).setOnClickListener(ClickClipBtnListener(this@MainActivity))
            findViewById<ImageButton>(R.id.clickBrowse).setOnClickListener(ClickBrowseBtnListener(this@MainActivity))
            findViewById<Switch>(R.id.secondaryDecode).setOnCheckedChangeListener { _, isChecked ->
                val numInput = findViewById<EditText>(R.id.secondaryDecodeDepth)
                if (isChecked) {
                    numInput.visibility = VISIBLE
                    numInput.setText("1")
                }
                else
                    numInput.visibility = INVISIBLE
            }
            findViewById<TextView>(R.id.debugWindow).movementMethod = ScrollingMovementMethod.getInstance()

            debug("启动成功!亲亲!")
            debug("使用此，请先输入待转换URL，选择是否自动转换跳转链接，然后点击按钮!")
            debug("点击按钮，即代表您已同意 《SinaURLDecoder使用手册》(并没有)")
            debug("已知bug: 在转换深度内不输入任何值或输入负值会导致崩溃")
            debug("判断: 良性bug，有强制值为signed之作用，妙哉(懒")
        }
    }
    fun debug(text: String?) {
        MainScope().launch(){
            val debugWin = findViewById<TextView>(R.id.debugWindow)
            val orig = debugWin.text?.toString() ?: ""
            debugWin.refreshDrawableState()
            debugWin.text = buildString {
                append(orig)
                append("\n")
                append(text)
            }

            val offset = debugWin.lineCount * debugWin.lineHeight - debugWin.lineHeight * 7
            debugWin.scrollTo(0, offset)
            debugWin.scrollY

            text?.let { Log.i(null, it) }
        }
    }

}